<template>
  <div class="product-detail" v-loading="loading">
    <div v-if="product" class="detail-container">
      <!-- 上部分：商品图片和信息 -->
      <div class="product-main">
        <div class="product-gallery">
          <el-carousel :interval="4000" type="card" height="400px">
            <el-carousel-item>
              <img :src="getImageUrl(product.imageUrl)" class="carousel-image" />
            </el-carousel-item>
          </el-carousel>
        </div>

        <div class="product-info">
          <h1 class="product-name">{{ product.name }}</h1>
          <div class="product-price">¥{{ product.price }}
            <span v-if="product.discountType === 'BIRTHDAY'" style="color:#e67e22;font-weight:bold;margin-left:8px;">
              生日特权价：¥{{ product.birthdayPrice }}
              <el-tag type="success" size="small">8折+积分翻倍</el-tag>
            </span>
            <span v-else-if="product.discountType === 'MEMBER'" style="color:#409eff;font-weight:bold;margin-left:8px;">
              会员价：¥{{ product.memberPrice }}
              <el-tag type="info" size="small">{{ (product.discountRate * 100).toFixed(0) }}%</el-tag>
            </span>
          </div>

          <div class="product-meta">
            <div class="meta-item">
              <span class="label">商品类型：</span>
              <span class="value">{{ getProductTypeName(product.type) }}</span>
            </div>
            <div class="meta-item">
              <span class="label">库存：</span>
              <span class="value">{{ product.stock }}</span>
            </div>
            <div class="meta-item">
              <span class="label">积分：</span>
              <span class="value">{{ product.productPoints }}</span>
            </div>
          </div>

          <div class="product-description">
            <h3>商品描述</h3>
            <p>{{ product.description }}</p>
          </div>

          <div class="purchase-actions">
            <el-input-number
                v-model="quantity"
                :min="1"
                :max="product.stock"
                label="数量"
            />
            <div class="action-buttons">
              <el-button type="primary" size="large" @click="handleBuy">
                立即购买
              </el-button>
              <el-button type="danger" size="large" @click="handleAddToCart">
                加入购物车
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 下部分：商品评价 -->
      <div class="product-comments">
        <div class="comments-header">
          <h2>商品评价</h2>
          <div class="rating-summary">
            <span class="average-rating">平均评分：{{ averageRating.toFixed(1) }}</span>
            <el-button type="primary" @click="commentDialogVisible = true" v-if="isLoggedIn && !userComment">
              写评价
            </el-button>
            <el-button link @click="$router.push('/login')" v-else-if="!isLoggedIn">
              登录后评价
            </el-button>
          </div>
        </div>

        <!-- 评价列表 -->
        <div class="comments-list">
          <div v-if="comments.length === 0" class="no-comments">
            暂无评价
          </div>
          <div v-else v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-header">
              <span class="username">{{ comment.username }}</span>
              <span class="rating">
                <el-rate v-model="comment.rating" disabled />
              </span>
              <span class="time">{{ formatDate(comment.createTime) }}</span>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
            <div class="comment-images" v-if="comment.images && comment.images.length">
              <el-image
                  v-for="(image, index) in comment.images"
                  :key="index"
                  :src="image"
                  :preview-src-list="comment.images"
                  fit="cover"
                  class="comment-image"
              />
            </div>
            <div class="comment-actions" v-if="comment.userId === userStore.userId">
              <el-button type="danger" size="small" @click="deleteComment(comment.id)">
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 购买对话框 -->
      <el-dialog v-model="buyDialogVisible" title="确认订单" width="500px">
        <el-form :model="orderForm" label-width="100px">
          <el-form-item label="收货地址">
            <el-input v-model="orderForm.address" />
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input v-model="orderForm.contactPhone" />
          </el-form-item>
          <el-form-item label="支付方式">
            <el-select v-model="orderForm.paymentMethod">
              <el-option label="支付宝" value="ALIPAY" />
              <el-option label="微信支付" value="WECHAT" />
              <el-option label="信用卡" value="CREDIT_CARD" />
              <el-option label="借记卡" value="DEBIT_CARD" />
              <el-option label="现金" value="CASH" />
              <el-option label="银行转账" value="BANK_TRANSFER" />
            </el-select>
          </el-form-item>
          <el-form-item label="运送方式">
            <el-select v-model="orderForm.shippingMethod">
              <el-option label="快递" value="EXPRESS" />
              <el-option label="标准配送" value="STANDARD" />
              <el-option label="自提" value="PICKUP" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="buyDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitOrder" :loading="submitting">
              确认下单
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 评价对话框 -->
      <el-dialog
          v-model="commentDialogVisible"
          title="写评价"
          width="500px"
      >
        <el-form :model="commentForm" label-width="80px" :rules="commentRules">
          <el-form-item label="评分">
            <el-rate v-model="commentForm.rating" />
          </el-form-item>
          <el-form-item label="评价内容">
            <el-input
                v-model="commentForm.content"
                type="textarea"
                :rows="4"
                placeholder="请输入评价内容"
            />
          </el-form-item>
          <el-form-item label="上传图片">
            <el-upload
                action="/api/upload"
                list-type="picture-card"
                :on-success="(res) => commentForm.images.push(res.data)"
                :on-remove="(file) => {
                const index = commentForm.images.indexOf(file.url)
                if (index > -1) {
                  commentForm.images.splice(index, 1)
                }
              }"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="commentDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitComment" :loading="submitting">
              提交评价
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getProductDetail as fetchProductDetail } from '@/api/product'
import { addToCart } from '@/api/cart'
import { createOrder } from '@/api/order'
import { useUserStore } from '@/stores/user'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const submitting = ref(false)
const product = ref(null)
const comments = ref([])
const quantity = ref(1)
const averageRating = ref(0)
const userComment = ref(null)
const commentDialogVisible = ref(false)
const buyDialogVisible = ref(false)
const commentForm = ref({
  content: '',
  rating: 5,
  images: []
})

const orderForm = ref({
  address: '',
  contactPhone: '',
  paymentMethod: 'ALIPAY',
  shippingMethod: 'EXPRESS',
  remarks: ''
})

const commentRules = {
  content: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 5, max: 500, message: '评价内容长度在 5 到 500 个字符', trigger: 'blur' }
  ],
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' },
    { type: 'number', min: 1, max: 5, message: '评分必须在1-5之间', trigger: 'change' }
  ]
}

const isLoggedIn = computed(() => userStore.isLoggedIn)

// 监听用户登录状态变化
watch(() => userStore.isLoggedIn, (newValue) => {
  if (newValue) {
    getUserComment()
  } else {
    userComment.value = null
  }
})

onMounted(async () => {
  try {
    loading.value = true
    await loadProductDetail()
    await getComments()
    await getAverageRating()
    // 只在用户已登录时获取用户评价
    if (userStore.isLoggedIn) {
      await getUserComment()
    }
  } catch (error) {
    console.error('加载商品详情失败:', error)
    ElMessage.error('加载商品详情失败')
  } finally {
    loading.value = false
  }
})

const loadProductDetail = async () => {
  loading.value = true
  try {
    const res = await fetchProductDetail(route.params.id)
    product.value = res.data
  } catch (error) {
    console.error(error)
    ElMessage.error('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

const handleBuy = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  buyDialogVisible.value = true
}

const handleAddToCart = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    await addToCart({
      productId: product.value.id,
      quantity: quantity.value,
      productName: product.value.name,
      price: product.value.price,
      image: product.value.imageUrl
    })
    ElMessage.success('已加入购物车')
  } catch (error) {
    console.error(error)
    ElMessage.error('加入购物车失败')
  }
}

const getComments = async () => {
  try {
    const res = await request.get(`/comments/product/${route.params.id}`, {
      headers: {
        'X-Skip-Auth': 'true'  // 跳过认证
      }
    })
    comments.value = res.data
  } catch (error) {
    console.error('获取商品评价失败:', error)
    if (error.response && error.response.status === 401) {
      ElMessage.warning('请先登录')
      router.push('/login')
    } else {
      ElMessage.error('获取商品评价失败')
    }
  }
}

const getAverageRating = async () => {
  try {
    const res = await request.get(`/comments/product/${route.params.id}/rating`, {
      headers: {
        'X-Skip-Auth': 'true'  // 跳过认证
      }
    })
    averageRating.value = res.data
  } catch (error) {
    console.error('获取商品评分失败:', error)
    if (error.response && error.response.status === 401) {
      ElMessage.warning('请先登录')
      router.push('/login')
    } else {
      ElMessage.error('获取商品评分失败')
    }
  }
}

const getUserComment = async () => {
  // 确保用户已登录且有用户ID
  if (!userStore.isLoggedIn || !userStore.userId) {
    userComment.value = null
    return
  }

  try {
    const res = await request.get(`/comments/user/${userStore.userId}/product/${route.params.id}`)
    userComment.value = res.data
  } catch (error) {
    console.error('获取用户评价失败:', error)
    // 如果是404错误，说明用户还没有评价，设置为null
    if (error.response && error.response.status === 404) {
      userComment.value = null
    } else if (error.response && error.response.status === 401) {
      ElMessage.warning('请先登录')
      router.push('/login')
    } else {
      ElMessage.error('获取用户评价失败')
    }
  }
}

const submitComment = async () => {
  // 确保用户已登录且有用户ID
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push({
      path: '/login',
      query: { redirect: router.currentRoute.value.fullPath }
    })
    return
  }

  // 检查token有效性
  const isValid = await userStore.checkTokenValidity()
  if (!isValid) {
    ElMessage.warning('登录已过期，请重新登录')
    router.push({
      path: '/login',
      query: { redirect: router.currentRoute.value.fullPath }
    })
    return
  }

  // 表单验证
  if (!commentForm.value.content || commentForm.value.content.trim().length < 5) {
    ElMessage.warning('评价内容不能为空且长度不能少于5个字符')
    return
  }

  if (!commentForm.value.rating || commentForm.value.rating < 1 || commentForm.value.rating > 5) {
    ElMessage.warning('请选择1-5之间的评分')
    return
  }

  try {
    submitting.value = true
    const comment = {
      productId: product.value.id,
      content: commentForm.value.content.trim(),
      rating: Number(commentForm.value.rating),
      images: Array.isArray(commentForm.value.images) ? commentForm.value.images : []
    }

    await request.post('/comments', comment)
    ElMessage.success('评价成功')
    commentDialogVisible.value = false
    // 重置表单
    commentForm.value = {
      content: '',
      rating: 5,
      images: []
    }
    // 刷新评论列表
    await Promise.all([
      getComments(),
      getAverageRating(),
      getUserComment()
    ])
  } catch (error) {
    console.error('提交评价失败:', error)
    if (error.response?.status === 401) {
      ElMessage.warning('登录已过期，请重新登录')
      router.push({
        path: '/login',
        query: { redirect: router.currentRoute.value.fullPath }
      })
    } else {
      ElMessage.error(error.response?.data?.message || '提交评价失败')
    }
  } finally {
    submitting.value = false
  }
}

const deleteComment = async (commentId) => {
  // 确保用户已登录且有用户ID
  if (!userStore.isLoggedIn || !userStore.userId) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    await request.delete(`/comments/${commentId}?userId=${userStore.userId}`)
    ElMessage.success('删除评价成功')
    await getComments()
    await getAverageRating()
    await getUserComment()
  } catch (error) {
    console.error('删除评价失败:', error)
    if (error.response && error.response.status === 401) {
      ElMessage.warning('请先登录')
      router.push('/login')
    } else {
      ElMessage.error('删除评价失败')
    }
  }
}

const submitOrder = async () => {
  // 检查用户是否登录
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push({
      path: '/login',
      query: { redirect: router.currentRoute.value.fullPath }
    })
    return
  }

  // 确保用户信息已加载
  const userInfoLoaded = await userStore.ensureUserInfoLoaded()
  if (!userInfoLoaded) {
    ElMessage.error('获取用户信息失败，请重新登录')
    userStore.logout()
    router.push({
      path: '/login',
      query: { redirect: router.currentRoute.value.fullPath }
    })
    return
  }

  // 表单验证
  if (!orderForm.value.address || !orderForm.value.contactPhone) {
    ElMessage.warning('请填写完整的收货信息')
    return
  }

  if (!orderForm.value.paymentMethod) {
    ElMessage.warning('请选择支付方式')
    return
  }

  if (!orderForm.value.shippingMethod) {
    ElMessage.warning('请选择运送方式')
    return
  }

  submitting.value = true
  try {
    const orderData = {
      userId: userStore.userId,
      productId: product.value.id,
      quantity: quantity.value,
      address: orderForm.value.address,
      contactPhone: orderForm.value.contactPhone,
      paymentMethod: orderForm.value.paymentMethod,
      shippingMethod: orderForm.value.shippingMethod,
      remarks: orderForm.value.remarks || '',
      orderStatus: 'PENDING',
      totalAmount: Number(product.value.price) * Number(quantity.value),
      orderPoints: Number(product.value.productPoints) * Number(quantity.value)
    }

    await createOrder(orderData)
    ElMessage.success('下单成功')
    buyDialogVisible.value = false
    router.push('/orders')
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.warning('登录已过期，请重新登录')
      router.push({
        path: '/login',
        query: { redirect: router.currentRoute.value.fullPath }
      })
    } else {
      ElMessage.error(error.response?.data?.message || '下单失败，请稍后重试')
    }
  } finally {
    submitting.value = false
  }
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 处理图片URL
const getImageUrl = (url) => {
  if (!url) return defaultProductImage
  if (url.startsWith('http')) return url
  if (url.startsWith('/uploads/')) return `http://localhost:8080${url}`
  return `http://localhost:8080/uploads/${url}`
}

const getProductTypeName = (type) => {
  const typeMap = {
    'ELECTRONICS': '电子产品',
    'CLOTHING': '服装',
    'FOOD': '食品',
    'BOOKS': '图书',
    'HOME': '家居',
    'SPORTS': '运动',
    'BEAUTY': '美妆',
    'OTHER': '其他'
  }
  return typeMap[type] || type
}
</script>

<style scoped>
.product-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.product-main {
  display: flex;
  gap: 40px;
  margin-bottom: 40px;
}

.product-gallery {
  flex: 1;
  min-width: 0;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.product-price {
  font-size: 28px;
  color: #f56c6c;
  margin-bottom: 20px;
}

.product-meta {
  margin-bottom: 20px;
}

.meta-item {
  margin-bottom: 10px;
  color: #666;
}

.meta-item .label {
  color: #999;
  margin-right: 10px;
}

.product-description {
  margin-bottom: 30px;
}

.product-description h3 {
  font-size: 18px;
  margin-bottom: 10px;
  color: #333;
}

.product-description p {
  color: #666;
  line-height: 1.6;
}

.purchase-actions {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.action-buttons {
  display: flex;
  gap: 20px;
}

.product-comments {
  margin-top: 40px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.rating-summary {
  display: flex;
  align-items: center;
  gap: 20px;
}

.average-rating {
  font-size: 16px;
  color: #666;
}

.comments-list {
  margin-top: 20px;
}

.comment-item {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.username {
  font-weight: bold;
  color: #333;
}

.rating {
  display: flex;
  align-items: center;
}

.time {
  color: #909399;
  font-size: 12px;
}

.comment-content {
  margin: 10px 0;
  color: #606266;
  line-height: 1.6;
}

.comment-images {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.comment-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
}

.comment-actions {
  margin-top: 10px;
  text-align: right;
}

.no-comments {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.buy-dialog {
  margin-top: 40px;
}

/* 修改轮播图样式 */
:deep(.el-carousel__container) {
  height: 400px;
}

:deep(.el-carousel__item) {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

:deep(.el-carousel__item img) {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
</style> 